package ce.service;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.hibernate.SessionFactory;

import net.bat.db.BaseDAOImpl;

//import net.bat.db.DBHelper;
import net.bat.util.Cfg;
import net.cs.um.UMService;
//import sharktc.presentation.SessionListener;
//import sharktc.presentation.SharkTCSessionData;
//import avens.AvensEngineManager;
//import avens.WfActivityImpl;
//import avens.WfProcessMgrImpl;
//import avens.omgapi.WfBase.BaseException;
//import avens.omgapi.WfBase.NameValue;
//import avens.omgapi.WorkflowModel.WfActivity;
//import avens.omgapi.WorkflowModel.WfAssignment;
//import avens.omgapi.WorkflowModel.WfProcess;
//import avens.omgapi.WorkflowModel.WfProcessMgr;
//import avens.omgapi.WorkflowService.WfProcessMgrIterator;
//import avens.persistence.PersistentManagerWrapper;
//import avens.persistence.dao.DAO;
//import avens.server.ProcessInstantiator;
//import avens.util.Session;
//import avens.util.SessionUtil;
import dao.hb.AvensParticipantmapping;
//import dao.hb.AvensResource;
import dao.hb.UGroup;
import dao.hb.UUser;
import ce.presentation.*;

public class AvensHlp<T>{
	
	private static BaseDAOImpl dao = null;
	
	//private static DBHelper dBHelper = (DBHelper) Cfg.getBean("DBHelper");
	public static BaseDAOImpl getDao() {
		if (dao == null)
			dao = (BaseDAOImpl) Cfg.getBean("BaseDAOImpl");
		return dao;
	}

	public static void setDao(BaseDAOImpl dao) {
		AvensHlp.dao = dao;
	}
	
	static public boolean isNumeric(String str){
		  for (int i = str.length();--i>=0;){  
		   if (!Character.isDigit(str.charAt(i))){
		    return false;
		    }
		   }
		  return true;
		}
	
	static public Integer toNum(String str){
		Integer istr=0;
		String newStr = "";
		for(int k=0; k < str.length(); k++){
		      int chr=str.charAt(k);
		       if(chr<48 || chr>57)
		        continue;
		       else{
		    	   newStr +=(char)chr;
		       }
		       if (k==8) break;
		    }
		if (isNumeric(newStr)) {
		    istr= (Integer)Integer.parseInt(newStr) ;
		}
		return istr;
	}
	
	/*
	 * 判断用户是否有效 如有效，则获取该用户的角色信息
	 * user : "cn=110108198103096884"
	 */
	static public String login(String userId, String pwd, String pwdNew,
			HttpServletRequest request) throws Exception {
		if (request.getSession().getAttribute(SessionListener.SESSION_KEY) != null)
			request.getSession().removeAttribute(SessionListener.SESSION_KEY);
		if (request.getSession().getAttribute(SharkTCSessionData.SESSION_KEY) != null)
			request.getSession().removeAttribute(SharkTCSessionData.SESSION_KEY);
		
		request.getSession().setAttribute("userId", userId);  //"cn=110108198103096884"
		SessionUtil.currentSession().setCurrentUser(userId);
//		AvensResource ar = (AvensResource) getDao().get(
//				"dao.hb.AvensResource", user);                       //wjh 2013.9
		//Class clazz = Class.forName("dao.hb.AvensResource");
//		Class clazz = dao.hb.AvensResource.class;
//		AvensResource ar = (AvensResource) dBHelper.get(
//				clazz, user);   
		//AvensResource ar  = (AvensResource)getDao().get(AvensResource.class, (Serializable)user); //user : cn=110102641211331
		
		String strHQL = "From UUser Where userId=?"; 	
		List results = getDao().find(strHQL,new String[] { userId});
		UUser uuser=null;
		if ((results!=null) && (results.size() > 0)) {
			uuser = (UUser)results.get(0);			
		}
		//UUser robj = (UUser)getDao.find(strHQL).setString("userId",username).uniqueResult(); 
		
		//return this.getHibernateTemplate().get(cls, id);
		if (uuser == null)
			throw new Exception("无效的用户");
		if (pwd != null) {
			if (uuser.getPwd() != null && !uuser.getPwd().equals(pwd))
				throw new Exception("无效的密码");
			pwd = null;// 避免后续处理清空avens_resource的org
		}
		String gid = String.valueOf(uuser.getGid());
		String roles = GetUGroup(gid);   //roles : DEV

System.out.println("********roles="+roles); //roles=DEV


		UMService.loginWithUser((BaseDAOImpl)getDao(),uuser,request,null);

//String suser = userId.substring(3);
//Integer iuser = toNum(suser)
//		int iuser=uuser.getId();
//		request.getSession().setAttribute(Cfg.SESSION_USER, iuser);	//1902	
//		UMService.putUserId(request.getSession().getId(),iuser);
		
		return roles;          //roles : DEV                   //"dpm_ce;;dpm_ce_djr";
	}

	// add chenlh
	/*
	 * username和participantId必须传一个，并且返回的顺序不是固定的
	 * 之所以这样，是使用了map，而同样的字符串作为key，只能得到一个实体
	 * 现在返回的这个map主要是个list的作用，也就是只有map的key列有实际意义
	 */
	public static Map GetParticipantMappings(String packageId,
			String processDefinitionId, String participantId, String username)
			throws Throwable {
		Map ret = new LinkedHashMap();
		if (username == null && participantId == null)
			throw new Exception("username和participantId必须传一个");
		if (username != null && participantId != null)
			System.out.println("\n\n注意：你同时传递了两个参数，返回结构的顺序要注意 \n\n\n");
		try {
			String filter = "";
			Map map = new HashMap();
			if (packageId != null) {
				filter += "packageId ='" + packageId + "'";
			}
			if (processDefinitionId != null) {
				if (!filter.equals(""))
					filter += "  and ";
				filter += "processDefinitionId = '" + processDefinitionId + "'";
			}
			if (participantId != null) {
				if (!filter.equals(""))
					filter += "  and ";
				filter += "participantId ='" + participantId + "'";
			}
			if (username != null) {
				if (!filter.equals(""))
					filter += "  and ";
				filter += "username = '" + username + "'";
			}
			String final_hql = "select distinct pm from dao.hb.AvensParticipantmapping as pm where "
					+ filter;
//			List results = DBHelper.getDAO().find(final_hql);
			List results = getDao().find(final_hql);
			Iterator iter = results.iterator();
			while (iter.hasNext()) {
				AvensParticipantmapping pm = null;
				pm = (AvensParticipantmapping) iter.next();
				String _packageId = pm.getPackageid();
				String _processDefinitionId = null;
				try {
					_processDefinitionId = pm.getProcessdefinitionid();
				} catch (Exception ex) {
				}
				if (_processDefinitionId == null
						|| _processDefinitionId.equals("null"))
					_processDefinitionId = "";
				String _participantId = pm.getParticipantid();
				String _username = pm.getUsername();
				StringBuffer str = new StringBuffer();
				str.append(_packageId);
				str.append(";");
				if ("*".equals(_processDefinitionId))
					str.append("");
				else
					str.append(_processDefinitionId);
				str.append(";");
				str.append(_participantId);
				if (username == null)
					ret.put(_username, str.toString());
				else
					ret.put(str.toString(), _username);
			}

		} catch (Throwable ex) {
			ex.printStackTrace();
		} finally {
		}
		return ret;
	}


	//username : cn=110108198103096884
	public static String GetUGroup( String gid){
		//Map ret = new LinkedHashMap();
		String ret = "";

		try {

			String final_hql = "from dao.hb.UGroup where id="+gid;					
			
//			List results = DBHelper.getDAO().find(final_hql);
			List<UGroup> results =  getDao().find(final_hql);
			Iterator<UGroup> iter = results.iterator();
			while (iter.hasNext()) {
				UGroup pm = null;
				pm = (UGroup) iter.next();
				//String _packageId = pm.getPackageid();
				String name = pm.getName();  //DEV
				ret = name;
				break;

			}

		} catch (Throwable ex) {
			ex.printStackTrace();
		} finally {
		}
		return ret; //  DEV  {DEV=cn=110108198103096884}
	}

	
	/**
	 * 根据包id,流程定义id实例化流程
	 * 
	 * @param packageId
	 * @param pDefStr
	 * @return 流程实例化产生的工作单id数组
	 * @throws Exception
	 */
//	static public String[] createNewProcess(String packageId, String pDefStr)
//			throws Exception {
//		WfProcessMgr[] mgrs;
//		WfProcessMgr mgr;
//		;
//		WfProcess proc;
//		WfProcessMgrIterator mi = AvensEngineManager.getInstance()
//				.get_iterator_processmgr();
//		mi.set_query_expression("packageId.equals(\"" + packageId + "\") && "
//				+ "processDefinitionId.equals(\"" + pDefStr + "\")");
//		mgrs = mi.get_next_n_sequence(1);
//		if (mgrs == null || mgrs.length == 0) {
//			throw new BaseException();
//		}
//		mgr = mgrs[0];
//
//		ProcessInstantiator initiator = new ProcessInstantiator();
//		proc = ((WfProcessMgrImpl) mgr).create_process(initiator);
//		proc.start();
//		List nextActs = DAO.find(
//				"select act.id from Activity as act where act.processId = ?",
//				new String[] { proc.key() });
//		int len = nextActs.size();
//		/*
//		 * String[] rs = new String[len]; for(int i=0; i<len; i++){
//		 * rs[i]=nextActs.get(i).toString(); }
//		 */
//		// 因为第一个活动是虚活动 所以这么处理 直接拿第二个活动
//		String[] rs = new String[1];
//		rs[0] = nextActs.get(1).toString();
//		return rs;
//	}

	/**
	 * 提交活动
	 * 
	 * @param nv
	 *            流程上下文
	 * @param wi
	 *            工作单号
	 * @return 提交之后生成的工作单id数组
	 * @throws Exception
	 */
//	static public String[] completeAct(NameValue[] nv, String wi)
//			throws Exception {
//		WfActivity wa = PersistentManagerWrapper.getInstance().getActivity(wi);
//		WfActivityImpl act = (WfActivityImpl) wa;
//		Session s = SessionUtil.currentSession();
//		s.setCurrentActivityKey(wa.key());
//		s.setCurrentActivityName(((WfActivityImpl) wa).name());
//		s.setCurrentActivityDefId(((WfActivityImpl) wa)
//				.activity_definition_id());
//		s.setMainProcessId(((WfActivityImpl) wa).getMainProcessId());
//		act.set_process_context(nv);
//		wa.complete();
//		List nextActs = DAO
//				.find("select act.id from Activity as act where act.previousActivity = ?",
//						new String[] { wi });
//		int len = nextActs.size();
//		String[] rs = new String[len];
//		for (int i = 0; i < len; i++) {
//			rs[i] = nextActs.get(i).toString();
//		}
//		return rs;
//	}

	/**
	 * 根据工作单号和当前登录用户，获得Assignment
	 * 
	 * @param wi
	 *            工作单号
	 * @return
	 */
//	static public WfAssignment getAssignment(String wi, String user)
//			throws Exception {
//		/*
//		 * TODO 在实现待办列表时，我没有采用worklist，而是复用了自己实现的联合查询、检索、分页
//		 * 在已知workitemId和user的情况下不知如何获得WfAssignment
//		 */
//		WfAssignment wfass = null;
//		WfActivityImpl act = PersistentManagerWrapper.getInstance()
//				.getActivity(wi);
//		try {
//			WfAssignment[] asses = act.get_sequence_assignment(0);
//			for (int j = 0; j < asses.length; j++) {
//				WfAssignment ass = asses[j];
//				String username = ass.assignee().resource_key();
//				if (username != null && username.equals(user)) {
//					wfass = ass;
//					break;
//				}
//			}
//
//		} catch (Throwable tr) {
//			tr.printStackTrace();
//		}
//		return wfass;
//		// return null;
//	}

	/**
	 * 锁定/解锁工作单,取当前登录用户
	 * 
	 * @param wi
	 *            工作单号
	 * @param bLock
	 *            锁定/解锁
	 * @throws Exception
	 */
//	static public void set_accepted_status(String wi, boolean bLock)
//			throws Exception {
//		WfAssignment ass = getAssignment(wi, SessionUtil.currentSession()
//				.getCurrentUser());
//		ass.set_accepted_status(bLock);
//	}

}
